package cn.springcloud.fix.common.core.utils.digest;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;

@Slf4j
public class Md5Util {

    private static byte[] md5(String s) {
        MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes("UTF-8"));
            return algorithm.digest();
        } catch (Exception e) {
            log.error("MD5 Error...", e);
        }
        return null;
    }

    private static String toHex(byte hash[]) {
        if (hash == null) return null;

        StringBuilder buf = new StringBuilder(hash.length * 2);
        for (byte aHash : hash) {
            if ((aHash & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString(aHash & 0xff, 16));
        }
        return buf.toString();
    }

    public static String hash(String s) {
        try {
            return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return s;
        }
    }
}
